<template>
  <div class="layout-full">
    <div class="d-bar">
      <div class="d-bar-item">
        <span class="d-bar-text">
          {{ this.state.name }}&nbsp;<span class="d-text-small d-text-lightgray">(单元数量：{{ state.data.units.length }})</span>
        </span>
      </div>
      <div  class="d-bar-item d-bar-item-btns">
        <span class="d-form-group-xxs" style="margin-right:8px">
          <input v-model="matchKeyword" class="d-form-input" type="text" placeholder="输入关键字过滤" />
        </span>
        <span v-if="!isView" @click="handleAddNode" class="d-bar-text d-text-linker d-text-lightgray" style="margin-right:8px"><PlusRoundIcon title="添加" /></span>
        <!-- <span v-if="!isView" @click="handleEdit" class="d-bar-text d-text-linker d-text-theme" style="margin-right:8px"><EditIcon class="rotate" title="编辑" /></span>-->
        <span v-if="!isView" @click="handleSubmit" class="d-bar-text" style="margin-right:8px">
          <button class="d-btn d-btn-primary d-btn-xs" type="button">保存</button>
        </span>
        <span v-if="!isView" @click="handlePreview" class="d-bar-text" style="margin-right:8px">
          <button class="d-btn d-btn-default d-btn-xs" type="button">预览</button>
        </span>
        <span v-if="isView" @click="handleRun" class="d-bar-text" style="margin-right:8px">
          <button class="d-btn d-btn-primary d-btn-xs" type="button">运行</button>
        </span>
        <span v-if="((state.data||{}).config||{}).isCycle || isCycle" class="d-bar-text d-text-linker d-text-lightgray" style="margin-right:8px">
          <FlashLight />
        </span>
        <span @click="handleSettingExe" class="d-bar-text d-text-linker d-text-lightgray" style="margin-right:8px">
          <SettingIcon class="rotate" title="设置" />
        </span>
        <span @click="handleRefresh" class="d-bar-text d-text-linker d-text-lightgray" style="margin-right:8px">
          <RefreshIcon title="刷新" />
        </span>
        <span @click="handleBack"  class="d-bar-text d-text-linker d-text-lightgray">
          <ReturnIcon title="返回" />
        </span>
      </div>
    </div>
    <div class="pages">
      <Executor
        :execute="state"
        @editNode="handleEditUnit"
        @delNode="handleDelNode"
        @onInitRender="handleInitExecutor"
        :mode="isView ? 'view' : ''"
        ref="executorView" />
    </div>
    <Dialoger v-model="isShowUnit" :onConfirm="handleSubmitAddUnit" :dialogCls="'d-paner-lg'" title="选择单元">
      <template v-slot:body>
        <FormUnit ref="unitView" />
      </template>
    </Dialoger>
    <Dialoger v-model="isShowEditUnit" :onConfirm="handleConfirmEdit" :dialogCls="'d-paner-lg'" title="编辑单元">
      <template v-slot:body>
        <EditForm @onMounted="handleMounedEditForm" :isShowOrigin="true" ref="editUnitForm" />
      </template>
    </Dialoger>
    <Dialoger v-model="isShowExeSetting" :onConfirm="handleSubmitExeSetting" :dialogCls="'d-paner-lg'" title="设置">
      <template v-slot:body>
        <ExeSetting :config="state.data.config" ref="exeSettingView" />
      </template>
    </Dialoger>
  </div>
</template>

<script>
import { PanerForm } from '@daelui/vdog/dist/pages'
import { Dialoger, FormCalendar, FormSelecter } from '@daelui/vdog/dist/components'
import { EditIcon, DeleteIcon, PlusRoundIcon, SettingIcon, RefreshIcon, ReturnIcon } from '@daelui/vdog/dist/icons'
import { zh as locale } from '@daelui/dogjs/dist/locale'
import { objecter, strer, parser } from '@daelui/dogjs/dist/components'
import cuteSer from '../../../service/action/execute.action'
import unitSer from '../../../service/action/exeunit.action'
import { state } from '../../../service/stock/index.js'
import FormUnit from './form-unit.vue'
import Executor from './executor.vue'
import EditForm from '../exeunit/edit-form.vue'
import ExeSetting from '../exegroup/exe-setting.vue'
import FlashLight from '../../../components/flash-light'

export default {
  components: {
    PanerForm,
    FormSelecter,
    FormCalendar,
    Dialoger,
    EditIcon,
    DeleteIcon,
    PlusRoundIcon,
    SettingIcon,
    RefreshIcon,
    ReturnIcon,
    FormUnit,
    Executor,
    EditForm,
    ExeSetting,
    FlashLight
  },

  data () {
    return {
      isEdit: false, // 是否是编辑模式
      isView: false, // 是否是预览模式
      unitId: '',
      // 表单数据
      state: {
        id: '',
        name: '',
        productId: '',
        type: '',
        data: {units: []},
        description: '',
        status: 1,
        order: 1,
        updateTime: '',
        updateUser: '',
        createTime: '',
        createUser: ''
      },
      // 单元列表
      unitList: [],
      // 状态列表
      statusList: state.statusList,
      // 过滤关键字
      matchKeyword: '',
      // 显示单元列表
      isShowUnit: false,
      // 是否显示单元编辑
      isShowEditUnit: false,
      isShowExeSetting: false,
      // 当前编辑的单元
      editUnit: {},

      /* 预览 */
      // 是否周期
      isCycle: false
    }
  },

  methods: {
    /**
     * @funcition 初始化
    */
    initView () {
      let params = this.$route.params
      // 无id或预览
      if (!params.id) {
        this.isEdit = false
      } else { // 编辑
        this.isEdit = true
        // 预览模式
        if (/view/.test(this.$route.path)) {
          this.isView = true
        }
        // 查询单元列表
        unitSer.queryListPage({size: 1000}).then(res => {
          this.unitList = res.data.list
          this.unitList.unshift(state.customUnit)
        }).then(() => {
          this.loadItem(params.id)
        })
      }
    },
    /**
     * @function 加载数据
    */
    loadItem (id) {
      cuteSer.queryItem({ id }).then(result => {
        let execute = result.data || {}
        execute.data = parser.parse(execute.data, 'object', true)
        let units = execute.data.units
        units = Array.isArray(units) ? units : []
        execute.data.units = units
        let config = execute.data.config
        config = config || {}
        execute.data.config = config
        this.state = execute
        this.$refs.executorView.reload()
      })
    },

    /**
     * @function 获取单元
    */
    getUnit (id) {
      let unit = this.unitList.find(item => item.id === id)
      return unit
    },

    /**
     * @function 显示添加节点
    */
    handleAddNode () {
      this.isShowUnit = true
    },

    /**
     * @function 添加节点
    */
    handleSubmitAddUnit () {
      let view = this.$refs.unitView
      let unitId = view.unitId
      let unit = this.getUnit(unitId)
      if (!unit) {
        Dialoger.warn('未选择单元')
        return false
      }
      this.state.data.units.push({
        id: strer.utid(),
        name: unit.name,
        uid: unit.id,
        isExecutorOrigin: true,
        isInputOrigin: true,
        isOutputOrigin: true
      })
      this.$refs.executorView.reload()
    },
    /**
     * @function 编辑节点
    */
    handleEditUnit (node) {
      this.editUnit = node
      this.isShowEditUnit = true
    },
    /**
     * @function 编辑节点数据初始化
    */
    handleMounedEditForm () {
      this.$refs.editUnitForm.loadItem(this.editUnit)
    },
    /**
     * @function 确认编辑节点
    */
    handleConfirmEdit () {
      let form = this.$refs.editUnitForm
      let state = form.state
      delete state.createTime
      if (!form.valid()) {
        return false
      }
      let node = this.editUnit
      node.name = state.name
      node.executor = state.executor
      node.input = state.input
      node.output = state.output
      node.isExecutorOrigin = state.isExecutorOrigin
      node.isInputOrigin = state.isInputOrigin
      node.isOutputOrigin = state.isOutputOrigin
      node.isHidden = state.isHidden
      node.isCollapse = state.isCollapse
    },
    /**
     * @function 删除节点
    */
    handleDelNode (node) {
      Dialoger.confirm(locale.message.confirmDelete).then(b => {
        if (!b) {
          return false
        }
        this.state.data.units = this.state.data.units.filter(item => item.id !== node.id)
        this.$refs.executorView.reload()
      })
    },

    handleEdit () {},

    /**
     * @function 提交
    */
    handleSubmit () {
      let defer = null
      let execute = objecter.clone(this.state, {
        callProperty (val) {
          if (val && val.$set) {
            return false
          }
        }
      })
      delete execute.createTime
      execute.data.units.forEach(item => {
        delete item.stepStatus
      })
      execute.data = JSON.stringify(execute.data)
      // 编辑
      defer = cuteSer.editItem(execute)
      defer.then(result => {
        if (result.success) {
          Dialoger.success(locale.action.success)
        } else {
          Dialoger.danger(locale.action.fail)
        }
      })
    },

    /**
     * @function 重置
    */
    handleReset () {

    },

    /**
     * @funcition 刷新
    */
    handleRefresh () {
      this.initView()
    },

    /**
     * @funcition 添加流程节点
    */
    handleBack () {
      this.$router.push(this.getMicroRoute('/process/execute/list'))
    },

    /**
     * @function 预览
    */
    handlePreview () {
      this.$refs.executorView.handleRun()
    },

    /**
     * @function 执行
    */
    handleRun () {
      this.$refs.executorView.handleRun()
    },

    /**
     * @function 设置组
    */
    handleSettingExe () {
      this.isShowExeSetting = true
    },

    /**
     * @function 保存设置
    */
    handleSubmitExeSetting () {
      let config = this.$refs.exeSettingView.getValue()
      this.state.data.config = Object.assign(this.state.data.config || {}, config)
      // 周期执行
      this.handleCycle()
    },

    /**
     * @function 切换周期执行
    */
    handleCycle () {
      this.$refs.executorView.handleCycle().then(b => {
        this.isCycle = b
      })
    },

    /**
     * @function 周期执行
    */
    runCycle () {
      this.$refs.executorView.runCycle()
    },

    /**
     * @function 停止周期执行
    */
    stopCycle () {
      this.$refs.executorView.stopCycle()
    },

    /**
     * @function 清除计时器
    */
    stopTimer () {
      this.$refs.executorView.stopTimer()
    },

    /**
     * @function 获取执行器初始化的结果
    */
    handleInitExecutor (view, isCycle) {
      this.isCycle = isCycle
    }
  },

  beforeMount () {
    // 初始化视图
    this.initView()
  }
}
</script>

<style lang="less" scoped>
.layout-full {
  flex: 1;
  width: 100%;
  height: 100%;
}
.d-bar {
  padding-left: 8px;
  padding-right: 8px;
  .d-bar-item-btns {
    font-size: 18px;
  }
  .d-bar-item {
    margin: 0;
  }
  .d-bar-item:first-child {
    flex-basis: 50%;
  }
  & + .pages {
    height: calc(~"100% - 38px");
  }
}
.d-list-item-icon {
  color: #999;
}
.item-text {
  overflow: hidden;
  max-width: 120px;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.icon-return {
  display: flex;
  align-items: center;
  font-size: 20px;
  color: #999;
  cursor: pointer;
}
.pages {
  flex: 1;
  margin-top: 8px;
  height: 100%;
  .d-paner-body {
    overflow: hidden;
  }
}
.pages-item {
  margin-top: 8px;
  .d-paner-body {
    min-height: 120px;
  }
}
.header-content {
  display: flex;
  width: 100%;
}
.d-bar-tools {
  overflow: visible;
  padding: 0;
}
.d-item-link {
  .d-icon-svg, .item-link-text {
    vertical-align: middle;
  }
  .item-link-text {
    margin-left: 8px;
  }
}
</style>
